package com.browsesoft.resource;

import java.util.Collection;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedList;

import com.browsesoft.EntityManager;
import com.browsesoft.Server;
import com.browsesoft.Tools;
import com.browsesoft.baseadapter.SimpleEntity;
import com.browsesoft.user.Organization;
import com.browsesoft.user.Role;
import com.browsesoft.user.User;

/**
 * 授权策略
 */
public class LicensePolicyEntity extends SimpleEntity {
	/**
	 * 
	 */
	private static final long serialVersionUID = -169950438395601544L;

	/**
	 * 授权资源
	 */
	private Resource resource;

	/**
	 * 被授权资源
	 */
	private Resource byResource;

	public LicensePolicyEntity() {
	}

	public LicensePolicyEntity(Hashtable ht) {
		super(ht);
	}

	/**
	 * 创建关系
	 */
	public void createRelation() {
		// 得到授权资源以及被授权资源
		String id = (String) this.attributes.get("resourceid");
		this.resource = (Resource) EntityManager.getInstance().getObject(id);
		id = (String) this.attributes.get("byresourceid");
		this.byResource = (Resource) EntityManager.getInstance().getObject(id);
	}

	public void setResource(Resource resource) {
		this.resource = resource;
	}

	public void setByResource(Resource byResource) {
		this.byResource = byResource;
	}

	public Resource getResource() {
		return this.resource;
	}

	public Resource getByResource() {
		return this.byResource;
	}

	/**
	 * 授权资源是否可继承
	 * 
	 * @return
	 */
	public boolean isInherit() {
		String isinherit = (String) this.getAttributes().get("isinherit");
		return isinherit != null && (isinherit.equals("是") || isinherit.equals("yes"));
	}

	/**
	 * 被授权资源是否可继承
	 * 
	 * @return
	 */
	public boolean isByInherit() {
		String isinherit = (String) this.getAttributes().get("byisinherit");
		return isinherit != null && (isinherit.equals("是") || isinherit.equals("yes"));
	}

	/**
	 * 得到所有过滤掉的资源号
	 */
	public Collection getFilterResourceIds() {
		String resourceResult = (String) this.attributes.get("resourceresult");
		if (resourceResult != null && !resourceResult.equals("")) {
			return Tools.stringToLinkedList(resourceResult);
		}
		return new LinkedList();
	}

	/**
	 * 得到所有过滤掉的被授权资源号
	 */
	public Collection getFilterByResourceIds() {
		String result = (String) this.attributes.get("byresourceresult");
		if (result != null && !result.equals("")) {
			return Tools.stringToLinkedList(result);
		}
		return new LinkedList();
	}

	/**
	 * 得到策略中所有授权资源
	 */
	public Collection getResources() {
		Collection result = new HashSet();
		String isinherit = (String) this.getAttributes().get("isinherit");
		if (resource != null) {
			result.add(resource);
			if (isinherit.equals("是")|| isinherit.equals("yes")) {
				result.addAll(resource.getAllChildrens());
				String resourceResult = (String) this.attributes
						.get("resourceresult");
				if (resourceResult != null && !resourceResult.equals("")) {
					String[] ids = resourceResult.split(",");
					for (int i = 0; i < ids.length; i++) {
						Resource r = (Resource) EntityManager.getInstance()
								.getObject(ids[i]);
						if (r != null) {
							result.remove(r);
							result.removeAll(r.getAllChildrens());
						}
					}
				}
			}
		}
		return result;
	}

	public Collection getByResources() {
		Collection result = new HashSet();
		String byisinherit = (String) this.getAttributes().get("byisinherit");
		if (byResource != null) {
			result.add(byResource);
			if (byisinherit.equals("是") || byisinherit.equals("yes")) {
				result.addAll(byResource.getAllChildrens());
				String byResourceResult = (String) this.attributes
						.get("byresourceresult");
				if (byResourceResult != null && !byResourceResult.equals("")) {
					String[] ids = byResourceResult.split(",");
					for (int i = 0; i < ids.length; i++) {
						Resource r = (Resource) EntityManager.getInstance()
								.getObject(ids[i]);
						if (r != null) {
							result.remove(r);
							result.removeAll(r.getAllChildrens());
						}
					}
				}
			}
		}
		return result;
	}

	public Resource getRemoteResource() throws Exception {
		String id = (String) this.attributes.get("resourceid");
		return (Resource) Server.getEntityManagerRMI().getObject(id);
	}

	public Resource getRemoteByResource() throws Exception {
		String id = (String) this.attributes.get("byresourceid");
		return (Resource) Server.getEntityManagerRMI().getObject(id);
	}

	public Collection getRemoteResources(Collection resources) throws Exception {
		Collection result = new HashSet();
		String isinherit = (String) this.getAttributes().get("isinherit");
		String id = (String) this.attributes.get("resourceid");
		Resource resource = this.getResource(resources, id);
		if (resource != null) {
			result.add(resource);
			if (isinherit.equals("是") || isinherit.equals("yes")) {
				result.addAll(resource.getAllChildrens());
				String resourceResult = (String) this.attributes
						.get("resourceresult");
				if (resourceResult != null && !resourceResult.equals("")) {
					String[] ids = resourceResult.split(",");
					for (int i = 0; i < ids.length; i++) {
						Resource r = this.getResource(resources, ids[i]);
						if (r != null) {
							result.remove(r);
							result.removeAll(r.getAllChildrens());
						}
					}
				}
			}
		}
		return result;
	}

	public Collection getRemoteByResources(Collection resources)
			throws Exception {
		Collection result = new HashSet();
		String byisinherit = (String) this.getAttributes().get("byisinherit");
		String id = (String) this.attributes.get("byresourceid");
		Resource byResource = this.getResource(resources, id);
		if (byResource != null) {
			result.add(byResource);
			if (byisinherit.equals("是") || byisinherit.equals("yes")) {
				result.addAll(byResource.getAllChildrens());
				String byResourceResult = (String) this.attributes
						.get("byresourceresult");
				if (byResourceResult != null && !byResourceResult.equals("")) {
					String[] ids = byResourceResult.split(",");
					for (int i = 0; i < ids.length; i++) {
						Resource r = this.getResource(resources, ids[i]);
						if (r != null) {
							result.remove(r);
							result.removeAll(r.getAllChildrens());
						}
					}
				}
			}
		}
		return result;
	}

	private Resource getResource(Collection resources, String id) {
		Iterator iter = resources.iterator();
		while (iter.hasNext()) {
			Resource item = (Resource) iter.next();
			if (item.getID().equals(id)) {
				return item;
			}
		}
		return null;
	}

	public Collection getRights() {
		String rightType = (String) this.attributes.get("righttype");
		return Tools.stringToLinkedList(rightType);
	}

	/**
	 * 看该策略的授权资源是否包含某资源
	 */
	public boolean containsResource(Resource rResource) {
		// 如果策略的授权资源与本资源相同，直接返回真
		Resource resource = this.getResource();
		// 如果策略中的授权资源为User
		if (resource instanceof User) {
			if (resource == rResource) {
				return true;
			}
		}
		// 如果策略中的授权资源是角色
		else if (resource instanceof Role) {
			if (((Role) resource).getUsers().contains((User) rResource)) {
				return true;
			}
		}
		// 如果授权资源可继承，且包含本资源，返回真
		return this.isInherit() && ResourceTool.contains(resource, rResource)
				&& !this.getFilterResourceIds().contains(rResource.getID());
	}

	/**
	 * 看该策略的被授权资源是否包含某资源
	 */
	public boolean containsByResource(Resource rResource) {
		// 如果策略的被授权资源与本资源相同，直接返回真
		Resource resource = this.getByResource();
		if (resource == rResource) {
			return true;
		}
		// 如果被授权资源可继承，且包含本资源，返回真
		return this.isByInherit() && ResourceTool.contains(resource, rResource)
				&& !this.getFilterByResourceIds().contains(rResource.getID());
	}

	/**
	 * 判断改权限的资源是否包含参数资源
	 */
	public boolean isContainerUser(User user) {
		// 得到本策略的资源
		if (this.resource != null) {
			return this.isContainerUser(this.resource, user);
		}
		return false;
	}

	public boolean isContainerUser(Resource resource, User user) {
		// 如果改资源时用户
		if (resource instanceof User) {
			return resource.equals(user);
		}
		// 如果是角色, 取角色里的用户
		else if (resource instanceof Role) {
			return ((Role) resource).getUsers().contains(user);
		} else {
			// 其它的，按树的层级关系取
			Resource parent = user.getParent();
			while (parent != null) {
				if (parent == resource) {
					return true;
				}
				parent = parent.getParent();
			}
		}
		return false;
	}

	/**
	 * 判断改资源是否过滤掉了
	 */
	public boolean isFilter(User user) {
		// 得到所有被过滤掉资源
		String ids = (String) this.getAttributes().get("resourceresult");
		LinkedList list = Tools.stringToLinkedList(ids);
		Iterator iter = list.iterator();
		while (iter.hasNext()) {
			String id = (String) iter.next();
			Object obj = EntityManager.getInstance().getObject(id);
			if (obj != null && this.isContainerUser((Resource) obj, user)) {
				return true;
			}
		}
		return false;
	}
}